import logging
from trade_system import TradeSystem
from auto_stable_01 import *  # 导入原文件所有功能

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    filename='trading_system_v2.log'
)
logger = logging.getLogger(__name__)

class StableTradingV2(StableTrading):
    """
    增强版交易系统，继承自原StableTrading类
    集成新的TradeSystem功能
    """
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        
        # 从原配置中提取数据库配置
        db_config = {
            "host": self.db_config.get("host", "localhost"),
            "user": self.db_config.get("user", "root"),
            "password": self.db_config.get("password", ""),
            "database": "trade_monitor_v2"
        }
        
        # 初始化交易系统
        self.trade_system = TradeSystem(db_config)
        
        # 止损相关配置
        self.stop_loss_ratio = 0.05  # 固定止损比例
        self.trailing_stop_ratio = 0.03  # 追踪止损比例
        self.use_fixed_stop_loss = True  # 默认使用固定止损
        
    def stop_loss(self, symbol, price):
        """实现止损逻辑"""
        # 限额止损
        if self.use_fixed_stop_loss:
            return self._fixed_stop_loss(symbol, price)
        # 均线追踪止损
        else:
            return self._moving_stop_loss(symbol, price)
            
    def _fixed_stop_loss(self, symbol, price):
        """限额止损实现"""
        positions = self.get_positions(symbol)
        for pos in positions:
            if pos['direction'] == 'long' and price <= pos['price'] * (1 - self.stop_loss_ratio):
                # 平多仓逻辑
                self.close_position(pos['position_id'], price)
            elif pos['direction'] == 'short' and price >= pos['price'] * (1 + self.stop_loss_ratio):
                # 平空仓逻辑
                self.close_position(pos['position_id'], price)
                
    def _moving_stop_loss(self, symbol, price):
        """均线追踪止损实现"""
        # 获取K线数据计算技术指标
        klines = self.get_klines(symbol)
        ma = self._calculate_moving_average(klines)
        
        positions = self.get_positions(symbol)
        for pos in positions:
            if pos['direction'] == 'long' and price <= ma * (1 - self.trailing_stop_ratio):
                # 平多仓逻辑
                self.close_position(pos['position_id'], price)
            elif pos['direction'] == 'short' and price >= ma * (1 + self.trailing_stop_ratio):
                # 平空仓逻辑
                self.close_position(pos['position_id'], price)
    
    async def on_order(self, order):
        """
        重写订单处理逻辑，集成新的交易系统
        """
        try:
            # 调用父类原有逻辑
            await super().on_order(order)
            
            # 使用新系统记录订单
            order_id = self.trade_system.create_order(
                user_id="system",  # 可根据实际需求修改
                product_id=order.symbol,
                direction="BUY" if order.direction == "BUY" else "SELL",
                offset_flag="OPEN" if order.offset == "OPEN" else "CLOSE",
                price=float(order.limit_price),
                volume=int(order.volume)
            )
            
            logger.info(f"订单已记录到新系统，ID: {order_id}")
            
        except Exception as e:
            logger.error(f"处理订单时出错: {str(e)}")
            
    def open_position(self, symbol, direction):
        """开仓逻辑"""
        # 检查持仓和未完成订单
        if not self._check_position_and_orders(symbol, direction):
            return False
            
        # 获取当前价格
        price = self.get_current_price(symbol)
        
        # 计算开仓手数
        volume = self._calculate_open_volume(symbol, direction, price)
        
        # 上海交易所品种特殊处理
        if self._is_shfe_symbol(symbol):
            return self._open_shfe_position(symbol, direction, price, volume)
        else:
            return self._open_normal_position(symbol, direction, price, volume)
            
    def _check_position_and_orders(self, symbol, direction):
        """检查持仓和未完成订单"""
        # 获取当前持仓
        positions = self.get_positions(symbol)
        # 获取未完成订单
        orders = self.get_orders(symbol, status='pending')
        
        # 检查逻辑...
        return True
        
    def _calculate_open_volume(self, symbol, direction, price):
        """计算开仓手数"""
        # 获取产品保证金
        margin = self.get_product_margin(symbol)
        # 计算可用资金
        available = self.get_available_funds()
        # 按20%可用资金计算目标持仓量
        target_volume = int((available * 0.2) / (price * margin))
        return max(1, target_volume)
    
    async def on_trade(self, trade):
        """
        重写成交处理逻辑，集成新的交易系统
        """
        try:
            # 调用父类原有逻辑
            await super().on_trade(trade)
            
            # 使用新系统记录成交
            record_id = self.trade_system.record_trade(
                order_id=trade.order_id,
                price=float(trade.price),
                volume=int(trade.volume)
            )
            
            # 更新持仓
            self.trade_system.update_position(
                user_id="system",
                product_id=trade.symbol,
                direction="LONG" if trade.direction == "BUY" else "SHORT",
                price=float(trade.price),
                volume=int(trade.volume)
            )
            
            logger.info(f"成交已记录到新系统，ID: {record_id}")
            
        except Exception as e:
            logger.error(f"处理成交时出错: {str(e)}")
    
    def get_positions(self):
        """
        获取持仓信息（新系统）
        """
        try:
            return self.trade_system.get_user_positions("system")
        except Exception as e:
            logger.error(f"获取持仓时出错: {str(e)}")
            return []
    
    def get_orders(self, status=None):
        """
        获取订单信息（新系统）
        """
        try:
            return self.trade_system.get_user_orders("system", status)
        except Exception as e:
            logger.error(f"获取订单时出错: {str(e)}")
            return []

# 保留原文件的main函数，但使用新类
def main():
    """
    主函数，使用增强版交易系统
    """
    trading = StableTradingV2()
    trading.run()

if __name__ == "__main__":
    main()